<?php
class MenuModel extends FW24H_Model {
	/**
	 * Enter description here...
	 *
	 * @var unknown_type
	 */
	var $tableName = '24hfw_menu';
	var $_primaryKey = 'menu_id';
	// Return menu array
	// Author: DungPT
	function categoryArray($id=0, $level=0) {
		$sql_add = "menu_parentid='$id'";
		
		$this->_cache = false;

		$cate = $this->find( $sql_add, '*', 'menu_order ASC');

		$nextLevel = $level + 1;
		for( $ii=0, $ss=sizeof( $cate); $ii<$ss; ++$ii) {
			$cate[$ii]['level'] = $level;
			$cate[$ii]['children'] = $this->categoryArray($cate[$ii]['menu_id'], $nextLevel);
		}
		return ( $cate);
	}
	function moveUp($mid){
		$arrMenu = $this->find("menu_id='$mid' AND menu_active=1", "*");
		$miOrder = intval($arrMenu[0]['menu_order'])-1;
		$arrPrevmenu = $this->find("menu_order <= '".$arrMenu[0]['menu_order']."' AND menu_parentid=".$arrMenu[0]['menu_parentid']." AND menu_id <>".$arrMenu[0]['menu_id'], "*", "menu_order DESC");
		
		// Update new position
		$this->update(array('menu_order'=>$miOrder), $mid);
		// Update prev menu to current position
		$this->update(array('menu_order'=>$arrMenu[0]['menu_order']), $arrPrevmenu[0]['menu_id']);
	}
	function moveDown($mid){
	
		$arrMenu = $this->find("menu_id='$mid' AND menu_active=1", "*");
		$miOrder = intval($arrMenu[0]['menu_order'])+1;
		$arrPrevmenu = $this->find("menu_order >= '".$arrMenu[0]['menu_order']."' AND menu_parentid=".$arrMenu[0]['menu_parentid']." AND menu_id <>".$arrMenu[0]['menu_id'], "*", "menu_order ASC");
		// echo '<pre>';print_r($arrPrevmenu );
		// Update new position
		$this->update(array('menu_order'=>$arrPrevmenu[0]['menu_order']), $mid);
		// Update prev menu to current position
		// echo $arrPrevmenu[0]['menu_id'];
		$this->update(array('menu_order'=>$arrMenu[0]['menu_order']), $arrPrevmenu[0]['menu_id']);
	}
	function parentMenu(){
		return $this->find("menu_parentid='0' AND menu_active=1", "*", "menu_order ASC");
	}
	// add menu
	function addMenu(){
		$biggestOrder = $this->find("menu_parentid='".$_POST['menu_parentid']."' AND menu_active=1", "menu_order", "menu_order DESC");
		if(sizeof($biggestOrder) <= 0){
			$_POST['menu_order'] = 1;
		}
		else{
			$_POST['menu_order'] = $biggestOrder[0]['menu_order'];
		}
		return $this->save($_POST);
	}
	// Update menu
	function updateMenu($mid, $arrData){
		$this->update($arrData, $mid);
	}
	// change status of menu
	function changeStatus($mid, $stat){
		$this->update(array('menu_active' => $stat), $mid);	
	}
	
	function menuInfo($mid){
		return $this->find('menu_id='.$mid, '*');
	}

	
	function getMenuFromLink( $link='') {
		return $this->find( 'menu_link= "'.$link.'"');
	}
}
